/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    int longestUnivaluePath(TreeNode *root)
    {
        this->maxLen = 0;
        longestSingleSideLenWithTotalMaxStorage(root);
        return this->maxLen;
    }

private:
    int maxLen = 0;
    int longestSingleSideLenWithTotalMaxStorage(TreeNode *root)
    {
        if (root == nullptr)
        {
            return 0;
        }
        int leftLen = 0;
        int rightLen = 0;
        if (root->left != nullptr)
        {
            int leftSubLen = longestSingleSideLenWithTotalMaxStorage(root->left);
            if (root->val == root->left->val)
            {
                leftLen = 1 + leftSubLen;
            }
        }
        if (root->right != nullptr)
        {
            int rightSubLen = longestSingleSideLenWithTotalMaxStorage(root->right);
            if (root->val == root->right->val)
            {
                rightLen = 1 + rightSubLen;
            }
        }
        int totalLen = leftLen + rightLen;
        this->maxLen = max(this->maxLen, totalLen);
        return max(leftLen, rightLen);
    }
};